package com.tim.app.ui.fragment.home;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.application.library.base.BaseFragment;
import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.refresh.PtrClassicFrameLayout;
import com.application.library.widget.refresh.PtrDefaultHandler;
import com.application.library.widget.refresh.PtrFrameLayout;
import com.application.library.widget.refresh.PtrHandler;
import com.application.library.widget.refresh.PtrUIHandler;
import com.application.library.widget.refresh.indicator.PtrIndicator;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.db.dao.DaoFactory;
import com.tim.app.server.api.API_Discover;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.entry.Advertisement;
import com.tim.app.server.entry.Article;
import com.tim.app.server.entry.Story;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.AdvertisementListResult;
import com.tim.app.server.result.ArticleListResult;
import com.tim.app.server.result.EveryDayHearListResult;
import com.tim.app.server.result.MusicAlbumListResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.SpecialListResult;
import com.tim.app.ui.activity.SearchActivity;
import com.tim.app.ui.activity.message.MessageActivity;
import com.tim.app.ui.activity.selected.ArticleDetailActivity;
import com.tim.app.ui.activity.selected.AskQuestionActivity;
import com.tim.app.ui.adapter.story.ArticleAdapter;
import com.tim.app.ui.view.FoundHeadView;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;

/**
 * 发现页面
 */
public class HomeFoundFragment extends BaseFragment implements View.OnClickListener, PtrHandler, LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "HomeFoundFragment";

    private View rootView;
    private PtrClassicFrameLayout refresh_layout;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvInfo;
    private EmptyLayout emptyLayout;
    private RelativeLayout rlHeader;
    private EditText etSearch;
    private ImageView ivNoticeIcon;

    private FoundHeadView foundHeadView;

    private ArticleAdapter adapter;
    private List<Article> dataList;

    private int pageNum = 1;//页码
    private int mDistance = 0;

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_tab_found, container, false);

            refresh_layout = (PtrClassicFrameLayout) rootView.findViewById(R.id.refresh_layout);

            load_more = (LoadMoreRecycleViewContainer) rootView.findViewById(R.id.load_more);
            wrvInfo = (WrapRecyclerView) rootView.findViewById(R.id.wrvInfo);
            wrvInfo.setOverScrollMode(View.OVER_SCROLL_NEVER);

            rlHeader = (RelativeLayout) rootView.findViewById(R.id.rlHeader);
            etSearch = (EditText) rootView.findViewById(R.id.etSearch);
            ivNoticeIcon = (ImageView) rootView.findViewById(R.id.ivNoticeIcon);

            ivNoticeIcon.setOnClickListener(this);
            etSearch.setOnClickListener(this);

            refresh_layout.disableWhenHorizontalMove(true);
            refresh_layout.addPtrUIHandler(new PtrUIHandler() {
                @Override
                public void onUIReset(PtrFrameLayout frame) {
                    rlHeader.setVisibility(View.VISIBLE);
                }

                @Override
                public void onUIRefreshPrepare(PtrFrameLayout frame) {
                    rlHeader.setVisibility(View.GONE);
                }

                @Override
                public void onUIRefreshBegin(PtrFrameLayout frame) {

                }

                @Override
                public void onUIRefreshComplete(PtrFrameLayout frame) {
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            rlHeader.setVisibility(View.VISIBLE);
                        }
                    }, 300);
                }

                @Override
                public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                    if (isUnderTouch) {
                        if (status == 1) {
                            rlHeader.setVisibility(View.VISIBLE);
                        } else {
                            rlHeader.setVisibility(View.GONE);
                        }
                    }
                }
            });
            refresh_layout.setPtrHandler(this);
            load_more.useDefaultFooter(View.GONE);
            load_more.setAutoLoadMore(true);
            load_more.setLoadMoreHandler(this);

            emptyLayout = new EmptyLayout(getActivity(), refresh_layout);
            emptyLayout.showLoading();
            emptyLayout.setEmptyButtonClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    emptyLayout.showLoading();
                    initData();
                }
            });
            dataList = new ArrayList<>();
            adapter = new ArticleAdapter(getActivity(), dataList);

            final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            wrvInfo.setLayoutManager(layoutManager);
            wrvInfo.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(getResources().getColor(R.color.view_background_color)).size((int) getResources().getDimension(R.dimen.splitLineHeight)).visibilityProvider(adapter).build());
            foundHeadView = (FoundHeadView) inflater.inflate(R.layout.found_head_view, wrvInfo, false);
            foundHeadView.setData(new ArrayList<Advertisement>());
            wrvInfo.addHeaderView(foundHeadView);
            wrvInfo.setAdapter(adapter);
            adapter.setOnItemClickListener(this);
            wrvInfo.setOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    mDistance += dy;

                    if (mDistance == 0) {
                        rlHeader.setBackgroundColor(getResources().getColor(R.color.transparent));
                        ivNoticeIcon.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.white_noitce_selector));
                    } else if (mDistance > 0 && mDistance < foundHeadView.getBannerView().getHeight()) {
                        rlHeader.setBackgroundColor(getResources().getColor(R.color.content_background_color));
                        ivNoticeIcon.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.white_noitce_selector));
                        if (mDistance < foundHeadView.getBannerView().getHeight()) {
                            int alpatValue = (int) ((float) mDistance / foundHeadView.getBannerView().getHeight() * 255);
                            rlHeader.getBackground().setAlpha(alpatValue);
                        }
                    } else {
                        ivNoticeIcon.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.noitce_selector));
                        rlHeader.setBackgroundColor(getResources().getColor(R.color.content_background_color));
                    }
                }

                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                }

            });
            initData();
        } else {
            if (refresh_layout != null) {
                refresh_layout.refreshComplete();
            }
        }
        showUnreadMesageView();
        EventManager.ins().registListener(EventTag.ON_MESSAGE_STATED_CHANGED, eventListener);
        EventManager.ins().registListener(EventTag.DO_REFRESH_FOUND, eventListener);
        EventManager.ins().registListener(EventTag.ACCOUNT_LOGIN, eventListener);
        EventManager.ins().registListener(EventTag.ACCOUNT_LOGOUT, eventListener);
        EventManager.ins().registListener(EventTag.GET_CURRENT_PLAY, eventListener);
        EventManager.ins().registListener(EventTag.ON_PLAY, eventListener);
        EventManager.ins().registListener(EventTag.ON_PAUSE, eventListener);
        EventManager.ins().registListener(EventTag.ON_STOP, eventListener);

        return rootView;
    }

    private void initData() {
        pageNum = 1;
        API_Found.ins().getArticleList(TAG, AppKey.TYPE_ARTICLE, false, false, false, pageNum, AppKey.PAGE_SIZE, CacheMode.REQUEST_FAILED_READ_CACHE, refreshCallback);
        initBannerData();
        initHotEveryDayData();
        initHotMusicAlbumData();
        initHotSpeciaData();
    }

    /**
     * 获取热门专题
     */
    private void initHotSpeciaData() {
        CacheMode cacheMode;
        if (UserManager.ins().getHotSpecialUpdateState()) {
            cacheMode = CacheMode.IF_NONE_CACHE_REQUEST;
        } else {
            cacheMode = CacheMode.NO_CACHE;
        }
        API_Discover.ins().getSpeciaList(TAG, 1, AppKey.PAGE_SIZE, cacheMode, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    SpecialListResult result = new Gson().fromJson(resultValue, SpecialListResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                        foundHeadView.setSpecialData(result.getRes().getArraylist().getResult());
                        UserManager.ins().updateHotSpecialUpdateState(true);
                    }
                }
                return false;
            }

        });
    }

    /**
     * 获取每日一听的数据
     */
    private void initHotEveryDayData() {
        CacheMode cacheMode;
        if (UserManager.ins().getEveryMusicUpdateState()) {
            cacheMode = CacheMode.IF_NONE_CACHE_REQUEST;
        } else {
            cacheMode = CacheMode.NO_CACHE;
        }
        API_Discover.ins().getHotEveryDayHearData(TAG, cacheMode, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    EveryDayHearListResult result = new Gson().fromJson(resultValue, EveryDayHearListResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getEverymusic().getStoryList()) {
                        foundHeadView.setEverydayStory(result.getRes().getEverymusic().getStoryList());
                        UserManager.ins().updateEveryMusicUpdateState(true);
                        emptyLayout.showContent();
                    }
                }
                return false;
            }
        });
    }

    /**
     * 获取音乐专辑的数据
     */
    private void initHotMusicAlbumData() {
        CacheMode cacheMode;
        if (UserManager.ins().getAlbumUpdateState()) {
            cacheMode = CacheMode.IF_NONE_CACHE_REQUEST;
        } else {
            cacheMode = CacheMode.NO_CACHE;
        }
        API_Discover.ins().getMusicAlbumList(TAG, 1, 6, cacheMode, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    MusicAlbumListResult result = new Gson().fromJson(resultValue, MusicAlbumListResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                        foundHeadView.setMusicAlbumData(result.getRes().getArraylist().getResult());
                        UserManager.ins().updateAlbumUpdateState(true);
                        emptyLayout.showContent();
                    }
                }
                return false;
            }
        });
    }

    /**
     * 获取广告数据
     */
    private void initBannerData() {
        CacheMode cacheMode;
        if (UserManager.ins().getBannerUpdateState()) {
            cacheMode = CacheMode.IF_NONE_CACHE_REQUEST;
        } else {
            cacheMode = CacheMode.NO_CACHE;
        }
        API_Found.ins().getAdvertisementList(TAG, AppKey.AD_TYPE_BANNER, cacheMode, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    AdvertisementListResult result = new Gson().fromJson(resultValue, AdvertisementListResult.class);
                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                        foundHeadView.setData(result.getRes().getArraylist());
                        UserManager.ins().updateBannerUpdateState(true);
                        emptyLayout.showContent();
                    }
                } else {
                    foundHeadView.setData(new ArrayList<Advertisement>());
                }
                return false;
            }
        });
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            refresh_layout.refreshComplete();
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                ArticleListResult result = new Gson().fromJson(resultValue, ArticleListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }

                if (dataList.size() == 0 && foundHeadView.isNull()) {
                    emptyLayout.showEmpty();
                } else {
                    emptyLayout.showContent();
                }
            } else {
                emptyLayout.showEmptyOrError(errCode);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                ArticleListResult result = new Gson().fromJson(resultValue, ArticleListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        EventManager.ins().removeListener(EventTag.ON_MESSAGE_STATED_CHANGED, eventListener);
        EventManager.ins().removeListener(EventTag.DO_REFRESH_FOUND, eventListener);
        EventManager.ins().removeListener(EventTag.ACCOUNT_LOGIN, eventListener);
        EventManager.ins().removeListener(EventTag.ACCOUNT_LOGOUT, eventListener);
        EventManager.ins().removeListener(EventTag.GET_CURRENT_PLAY, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PLAY, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PAUSE, eventListener);
        EventManager.ins().removeListener(EventTag.ON_STOP, eventListener);
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        if (null == dataList || position > dataList.size() - 1)
            return;
        Article article = dataList.get(position);
        ArticleDetailActivity.start(getContext(), article, false);
    }

    /**
     * 消息的view
     */
    private void showUnreadMesageView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final int unReadMessageTotalCount = NIMClient.getService(MsgService.class).getTotalUnreadCount();
                final int unReadNoticeCount = DaoFactory.getNoticeDao().getUnReadMessageCount();
                if (unReadMessageTotalCount > 0 || unReadNoticeCount > 0 || UserManager.ins().getUnreadOfficialMessageCount() > 0) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ivNoticeIcon.setSelected(true);
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivNoticeIcon:
                if (UserManager.ins().isLogin()) {
                    MessageActivity.start(getActivity());
                } else {
                    ViewGT.gotoLoginActivity(getActivity());
                }
                break;
            case R.id.etSearch:
                SearchActivity.start(getContext(), SearchActivity.SEARCH_ALL, "");
                break;
            case R.id.rlAnswer:
                EventManager.ins().sendEvent(EventTag.GOTO_ANSWER, 0, 0, null);
                break;
            case R.id.rlAskQuestion:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getContext());
                    return;
                }
                Intent intentAsk = new Intent(getContext(), AskQuestionActivity.class);
                intentAsk.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getContext().startActivity(intentAsk);
                break;
            default:
                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.DO_REFRESH_FOUND:
                    wrvInfo.scrollToPosition(0);
                    refresh_layout.autoRefresh();
                    break;
                case EventTag.ON_MESSAGE_STATED_CHANGED:
                    boolean isShow = (boolean) dataobj;
                    ivNoticeIcon.setSelected(isShow);
                    break;
                case EventTag.ACCOUNT_LOGOUT:
                    ivNoticeIcon.setSelected(false);
                    break;
                case EventTag.ACCOUNT_LOGIN:
                    showUnreadMesageView();
                    break;
                case EventTag.GET_CURRENT_PLAY:
                    int index = arg1;
                    int stated = arg2;
                    ArrayList<Story> storyList = (ArrayList<Story>) dataobj;
                    foundHeadView.setPlayData(index, storyList, stated);
                    break;
                case EventTag.ON_PLAY:
                    EventManager.ins().sendEvent(EventTag.ON_GET_CURRENT_PLAY, 0, 0, null);
                    break;
                case EventTag.ON_PAUSE:
                case EventTag.ON_STOP:
                    foundHeadView.updatePlayingStated(false);
                    break;
            }
        }
    };

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_Found.ins().getArticleList(TAG, AppKey.TYPE_ARTICLE, false, false, false, pageNum + 1, AppKey.PAGE_SIZE, CacheMode.REQUEST_FAILED_READ_CACHE, moreCallback);
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, wrvInfo, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        initData();
    }

}
